package com.diyunapp.xilinapp.utils;

import android.os.Handler;
import android.os.Message;

import com.orhanobut.logger.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class SmsThread extends Thread {
	private static final int SMS_SUCCESS = 11;
	private static final int SMS_FAIL = 12;
	private static final int HTTP_ERROR = 10;
	//TODO 替换参数
	private final static  String x_id = "lwrh0530";
	private final static  String x_pwd = "lwrh0530";
	private String mobile;
	private String content;
	private ResultListner resultListner;

	public SmsThread(String mobile, String content, ResultListner l) {
		super();
		this.mobile = mobile;
		this.content = content;
		this.resultListner = l;
	}



	@Override
	public void run() {
		Integer x_ac = 10;// 发送信息
		HttpURLConnection httpconn = null;
		String result = "-20";
		String memo = content.length() < 70 ? content.trim() : content.trim()
				.substring(0, 70);
		StringBuilder sb = new StringBuilder();
		sb.append("http://service.winic.org/sys_port/gateway/?");
		sb.append("id=").append(x_id);
		sb.append("&pwd=").append(x_pwd);
		sb.append("&to=").append(mobile);
		try {
			sb.append("&content=").append(URLEncoder.encode(content, "GB2312"));
		} catch (UnsupportedEncodingException e1) {
			Message msg = Message.obtain();
			msg.arg1 = SMS_FAIL;
			msg.obj = "短信内容有误";
			e1.printStackTrace();
		} // 注意乱码的话换成gb2312编码
		try {
			URL url = new URL(sb.toString());
			httpconn = (HttpURLConnection) url.openConnection();
			if(httpconn.getResponseCode() == 200) {
				InputStream is = httpconn.getInputStream();
				BufferedReader rd = new BufferedReader(new InputStreamReader(is));
				result = rd.readLine();
				rd.close();
				is.close();
				Logger.d("sms = " +result);
				String info = result.toString().substring(0, 2);
				if(info.endsWith("0")) {
					handler.sendEmptyMessage(SMS_SUCCESS);
				}
				else {
					handler.sendEmptyMessage(SMS_FAIL);
				}
			}
			else {
				handler.sendEmptyMessage(HTTP_ERROR);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (httpconn != null) {
				httpconn.disconnect();
				httpconn = null;
			}
		super.run();
		}
	}

	Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			switch (msg.what){

				case SMS_SUCCESS:
					resultListner.onSuccess("已发送！");
					break;
				case SMS_FAIL:
					resultListner.onFailed("发送失败！");
					break;
				case HTTP_ERROR:
					resultListner.onFailed("resp_code!=200");
					break;
				default:break;
			}
		}
	};

	public interface ResultListner{

		void onSuccess(String msg);
		void onFailed(String err);
	}
}
